package net.zjitc.dao.impl;

import net.zjitc.dao.CategoryDao;
import net.zjitc.pojo.Category;
import net.zjitc.utils.db.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by lenovo on 2017/11/24.
 */
public class CategoryDaoImpl implements CategoryDao{
    public List<Category> findAll() {
        QueryRunner runner=new QueryRunner(C3P0Utils.getDataSource());
        String sql="select * from category";
        List<Category> list=null;
        try {
            list= (List<Category>) runner.query(sql,new BeanListHandler(Category.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public int addCategory(String cname) {
        QueryRunner runner=new QueryRunner(C3P0Utils.getDataSource());
        String sql="insert into category(cname) values(?)";
        try {
            int count=runner.update(sql,cname);
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public int deleteCategory(String cid) {
        QueryRunner runner=new QueryRunner(C3P0Utils.getDataSource());
        String sql="delete from category where cid=?";
        try {
            int count=runner.update(sql,cid);
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public Category findByCid(String cid) {
        QueryRunner runner=new QueryRunner(C3P0Utils.getDataSource());
        String sql="select * from category where cid=?";
        Category category=null;
        try {
            category= (Category) runner.query(sql,new BeanHandler(Category.class),cid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return category;
    }

    public int editCategory(Category category) {
        QueryRunner runner=new QueryRunner(C3P0Utils.getDataSource());
        String sql="update category set cname=? where cid=?";
        try {
            int count=runner.update(sql,category.getCname(),category.getCid());
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
